#include "pagealarmmgmt.h"
#include "ui_pagealarmmgmt.h"
#include "alertmanager.h"
#include <QMessageBox>

pageAlarmMgmt::pageAlarmMgmt(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::pageAlarmMgmt)
{
    ui->setupUi(this);

    // Setup tab widget
    ui->tabWidget->setTabText(0, "告警规则");
    ui->tabWidget->setTabText(1, "告警记录");

    // Setup models
    ruleModel = new QSqlTableModel(this);
    recordModel = new QSqlTableModel(this);
    setupTables();

    // Connect buttons
    connect(ui->btnAdd, &QPushButton::clicked, this, &pageAlarmMgmt::onAddRule);
    connect(ui->btnDelete, &QPushButton::clicked, this, &pageAlarmMgmt::onDeleteRule);
}

void pageAlarmMgmt::setupTables() {
    // Rules table
    ruleModel->setTable("alarm_rules");
    ruleModel->select();
    ui->tblRules->setModel(ruleModel);
    ui->tblRules->hideColumn(0);  // Hide rule_id

    // Records table
    recordModel->setTable("alarm_records");
    recordModel->setSort(2, Qt::DescendingOrder);
    recordModel->select();
    ui->tblRecords->setModel(recordModel);
}

void pageAlarmMgmt::onAddRule() {
    // Get input values
    int deviceId = ui->spinDeviceId->value();
    QString desc = ui->txtDesc->text();
    QString condition = ui->cmbCondition->currentText();
    QString action = ui->txtAction->text();

    AlertManager am;
    if(am.addAlertRule(deviceId, desc, condition, action)) {
        refreshTables();
    }
}

void pageAlarmMgmt::onDeleteRule() {
    QModelIndex index = ui->tblRules->currentIndex();
    if(index.isValid()) {
        int ruleId = ruleModel->data(ruleModel->index(index.row(), 0)).toInt();
        AlertManager am;
        if(am.deleteAlertRule(ruleId)) {
            refreshTables();
        }
    }
}

void pageAlarmMgmt::refreshTables() {
    ruleModel->select();
    recordModel->select();
}

pageAlarmMgmt::~pageAlarmMgmt() {
    delete ui;
}
